package org.gfids.trivial.controller;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

import org.gfids.trivial.gui.AbstractGui;
import org.gfids.trivial.gui.GuiUpload;
import org.gfids.util.NetSession;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class Controlador implements ActionListener {
	private String server;
	private int port;
	private Properties props;

	private List<AbstractGui> registeredViews;

	public Controlador() {
		registeredViews = new ArrayList<AbstractGui>();
	}

	public Controlador(AbstractGui g) {
		try {
			props = new Properties();
			FileInputStream fis = new FileInputStream(System.getProperty("user.dir")+System.getProperty("file.separator")+"clienteConfig.properties");
			props.load(fis);
			fis.close();
		} catch (FileNotFoundException e) {
			javax.swing.JOptionPane.showMessageDialog(new javax.swing.JFrame(), "Fichero de configuracion no hallado");
		} catch (IOException e) {
			javax.swing.JOptionPane.showMessageDialog(new javax.swing.JFrame(), "Se dio un problema al cargar la configuracion");
		}


		Boolean produccion = Boolean.valueOf(props.getProperty("configActivada"));
		if(produccion) {
			server = props.getProperty("server");
			port= Integer.valueOf(props.getProperty("port"));
		} else {
			server = "www.ociorum.org";
			port = 7777;
		}

		new Controlador();
		registeredViews.add(g);
	}

	@Override
	public void actionPerformed(ActionEvent ae) {

		if(ae.getSource() instanceof JButton) { // Aqui vamos a crear el objeto cuestion y enviarlo por Socket

			for(AbstractGui g: registeredViews) {
				//if(g.getClass() instanceof GuiUpload.class) {
					NetSession ns = new NetSession(server, port);

					ns.send(((GuiUpload)g).getNewCuestion());
					if(null != ns.receive()) {
						javax.swing.JOptionPane.showMessageDialog(null, "Se ha subido la cuestion");
					}
				//}
			}
		}

	}


	/**
     * Binds a view to this controller. The controller will propogate all model property
     * changes to each view for consideration.
     * @param view The view to be added
     */
    public void addView(AbstractGui view) {
        registeredViews.add(view);
        view.addListener(this);
    }

    /**
     * Unbinds a view from this controller.
     * @param view The view to be removed
     */
    public void removeView(AbstractGui view) {
        registeredViews.remove(view);
    }

}
